define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'upload'], function ($, undefined, Backend, Table, Form, Upload) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'xilujob/resume/index' + location.search,
                    add_url: 'xilujob/resume/add',
                    edit_url: 'xilujob/resume/edit',
                    del_url: 'xilujob/resume/del',
                    multi_url: 'xilujob/resume/multi',
                    table: 'xilujob_resume',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                //启用固定列
                fixedColumns: true,
                //固定右侧列数
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'user_id', title: __('User_id')},
                        {field: 'user.mobile', title: __('User.mobile'), operate:'like'},
                        {field: 'personal.mobile', title: __('Personal.mobile'), operate:'like'},
                        {field: 'personal.realname', title: __('Personal.realname'),operate:'like'},
                        {field: 'personal.gender', title: __('Personal.gender'),formatter: function(value){return this.searchList[value];}, searchList: {1: '男', 2: '女'}},

                        {field: 'age', 'title':'年龄', operate:'BETWEEN', formatter: function (val, row) {
                                try {
                                    if(!row.personal.birthdate)
                                        return '';
                                    var birthdate = new Date(row.personal.birthdate).getTime();
                                    var now = new Date().getTime();
                                    return parseInt((now - birthdate) / 31536000000);
                                }catch (e) {
                                    return '';
                                }
                        }},

                        {field: 'personal.work_experience_id', title: '工作经验',searchList: Config.work_experience_options, formatter: function (val, row) {
                                try {
                                    for(var i=0;i<this.searchList.length;i++) {
                                        var item = this.searchList[i];
                                        if(item.id==val)
                                            return item.name;
                                    }
                                    return '';
                                }catch (e) {
                                    return '';
                                }
                            }},
                        {field: 'resume_files',title: __('简历附件'),formatter: function (value,row) {
                                if(value.length>0){
                                    var html = '';
                                    for(var i=0;i<value.length;i++){
                                        var file = value[i];
                                        if(file.file_ext.toLowerCase()  == 'pdf'){
                                            html += '<a href="'+file.file+'" target="_blank"><img class="img-sm img-center" src="'+Fast.api.fixurl('/assets/addons/xilujob/images/icon_file.png')+'" /></a><span></span>'
                                        }else if(file.file_ext.toLowerCase()  == 'doc' || file.file_ext.toLowerCase()  == 'docx') {
                                            html += '<a href="'+file.file+'" target="_blank"><img class="img-sm img-center" src="'+Fast.api.fixurl('/assets/addons/xilujob/images/icon_file.png')+'" /></a><span></span>'
                                        }else {
                                            html += '<a href="'+file.file+'" target="_blank"><img class="img-sm img-center" src="'+file.file+'" /></a><span></span>'
                                        }
                                    }
                                    return html;
                                }else{
                                    return '无附件简历';
                                }
                            },operate:false},
                        {field: 'personal.education_level_id', title: '学历', searchList:Config.education_level, formatter:function(val,row){return row.personal.education_level?row.personal.education_level.name:''}},
                        {field: 'complete_percent', title: ('完整度(%)'),operate:false,sortable:true},
                        {field: 'view_count', title: '浏览数',operate:false,sortable:true},
                        {field: 'fav_count', title: '收藏数',operate:false,sortable:true},
                        {field: 'refreshetime', title: __('刷新时间'),operate:'RANGE',addclass:'datetimerange',formatter:Table.api.formatter.datetime, sortable:true},
                        {field: 'top', title:'置顶', formatter: Table.api.formatter.input, sortable:true},
                        {field: 'black', title: '屏蔽',operate:false,formatter: Table.api.formatter.toggle},
                        {field: 'status', title: '显示',operate:false,formatter: Table.api.formatter.toggle},

                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate, buttons: [
                                {
                                    name: 'detail',
                                    title: __('查看'),
                                    extend: 'data-toggle="tooltip" data-area=\'["475px","100%"]\'',
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    icon: 'fa fa-eye',
                                    url: 'xilujob/resume/detail',
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    },
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        return true;
                                    }
                                },
                                {
                                    name: 'edit',
                                    title: __('编辑'),
                                    extend: 'data-toggle="tooltip" data-area=\'["90%","100%"]\'',
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    icon: 'fa fa-edit',
                                    url: 'xilujob/resume/edit',
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    },
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        return true;
                                    }
                                },
                            ]}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'xilujob/resume/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'xilujob/resume/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'xilujob/resume/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            let areas = Config.areas;
            var validatoroptions = {
                rules: {
                    'gt': function (element, params) {
                        var end = $(element).val();
                        var start = $(element).closest('.Jedu-row').find('input[name=start]').val();
                        if(end>start)
                            return true;
                        // element.scrollIntoView();
                        return '离职时间必须大于入职时间';
                    }
                },
                invalid: function (form, errors) {
                    $.each(errors, function (i, j) {
                        Toastr.error(j);
                    });
                }
            };

            require(['../addons/xilujob/js/vue','../addons/xilujob/js/util','../addons/xilujob/js/scroll-select'],function (Vue,Util) {
                var moduleRelationNames = {
                    'personal_info': 'personal',
                    'education':'educations',
                    'work':'works',
                    'personal_tag': 'personal_tags',
                    'job_intention':'job_intention',
                    'skill': 'skills',
                    'summary': 'summary'
                };
                try {
                    window.app = new Vue({
                        el: '#resume',
                        data: {
                            resume: resume,
                            editing: {
                                module: '',
                                model: {}//正在编辑的模型数据
                            },
                            tag_options: tagOptions,
                        },
                        computed: {
                            editingPersonal: function () {
                                return this.editing.module === 'personal_info';
                            },
                            editingJobIntention: function () {
                                return this.editing.module === 'job_intention';
                            },
                            editingEducation: function () {
                                return this.editing.module === 'education';
                            },
                            editingWork: function () {
                                return this.editing.module === 'work';
                            },
                            editingPersonalTag: function () {
                                return this.editing.module === 'personal_tag';
                            },
                            editingSkill: function () {
                                return this.editing.module === 'skill';
                            },
                            editingSummary: function () {
                                return this.editing.module === 'summary';
                            }
                        },
                        methods: {
                            cdnurl: function(url) {
                                if(url){
                                    return Fast.api.cdnurl(url);
                                }
                            },
                            /**
                             * 打开添加或编辑窗口
                             * @param moduleName string
                             * @param model object
                             */
                            edit: function (moduleName, model) {
                                this.editing.module = moduleName;
                                this.editing.model = {};
                                this.editing.model = JSON.parse(JSON.stringify(model));
                                setTimeout(function () {
                                    //触发textarea计算文字数量
                                    $('textarea').trigger('keyup');
                                    //触发自定义selector文本更新
                                    $('.ul-selector input:hidden').trigger('change');
                                    //触发scroll-select文本更新
                                    $('.select-job').each(function(){
                                        var ids = $(this).siblings('input:hidden').attr('data-ids')?$(this).siblings('input:hidden').attr('data-ids').replace(/,$/,''):'';
                                        ids = ids ? ids.split(',') : [];
                                        $(this).trigger('change', [ids]);
                                    });
                                }, 1);
                            },
                            closeEdit: function() {
                                this.editing.module = '';
                                this.editing.model = {};
                            },
                            del: function (moduleName, model) {
                                Layer.confirm('确定删除？', function (index) {
                                    Layer.close(index);
                                    Fast.api.ajax({
                                        url: 'xilujob/resume/del_module/resume_id/'+resume.id,
                                        data: {id: model.id, module: moduleName, resume_id: resume.id}
                                    }, function () {
                                        var moduleRelationName = moduleRelationNames[moduleName];
                                        var index = app.resume[moduleRelationName].indexOf(model);
                                        app.resume[moduleRelationName].splice(index, 1);
                                    })
                                });
                            },
                            // refresh_resume: function () {
                            //     Fast.api.ajax({url:'xilujob/my_resume/refresh_resume/id/'+this.resume.id},function (data,ret) {
                            //         app.resume.refreshed_at = data.resume.refreshed_at;
                            //         app.resume.refresh_date = data.resume.refresh_date;
                            //     });
                            // },
                            notPresetTag: function(tagName) {
                                for(var i=0;i<this.tag_options.length;i++) {
                                    var tag = this.tag_options[i];
                                    if(tag.name===tagName) {
                                        return false;
                                    }
                                }
                                return true;
                            },
                            /**
                             *
                             * @param {Object} tag
                             * @return {Boolean}
                             */
                            tagHighlight: function(tag) {
                                for(var i=0;i<this.editing.model.length;i++) {
                                    if(this.editing.model[i].name===tag.name) {
                                        return true;
                                    }
                                }
                                return false;
                            },
                            /**
                             *
                             * @param {Object} tag
                             */
                            toggle_tag: function (tag) {
                                var index = null;
                                for(var i=0;i<this.editing.model.length;i++) {
                                    if(this.editing.model[i].name===tag.name) {
                                        index = i;
                                        break;
                                    }
                                }
                                if(index!==null) {
                                    this.editing.model.splice(index,1);
                                }else {
                                    this.editing.model.push(tag);
                                }
                            }
                        }
                    });
                }catch(e) {
                    Toastr.error('简历数据异常');
                    return;
                }
                $('#resume').css('visibility','visible');
                //    滚动切换选中状态
                $(window).scroll(function(){
                    var scrollH = $(this).scrollTop();
                    for(var i=0;i<$('.Jbox').length;i++){
                        if(scrollH>$('.Jbox').eq(i).offset().top-100){
                            $(".sidebar li").removeClass('active');
                            $(".sidebar li").eq(i).addClass("active");
                        }
                    }
                });

                $(".textarea-count").on("keyup", function(){
                    var maxlength = $(this).attr('maxlength') || 100;
                    var text = $(this).val();
                    var num = text.length;
                    if (num > maxlength){
                        text = text.substring(0,maxlength);
                        $(this).val(text)
                    }
                    $(this).parents(".Jbox").find(".Jfrt").text(num +'/'+maxlength+' 字')
                });

                Util.bindSelect('.ul-selector');
                //头像
                Upload.api.plupload('#upload-avatar', function(data) {
                    var id = $('#upload-avatar').data('id');
                    var url =  data.url;//不带http的路径
                    Fast.api.ajax({
                        url: 'xilujob/resume/save_module/resume_id/'+resume.id,
                        data: {'module':'personal_info', avatar: url, id: id}
                    },function() {
                        $('#upload-avatar').siblings('img').attr('src', Fast.api.cdnurl(url));
                    });
                },function(data, error){
                    var msgs = {
                        '-600': '文件最大5M',
                    };
                    var msg = msgs[error.code] || error.msg;
                    Toastr.error(msg);
                    return false;
                });
                (function(){
                    //户籍选择省市
                    var cityPicker = new ScrollSelect({
                        data:areas, max_level:2,
                        on_select:function(rows, level) {
                            console.log(rows)
                            var value = [];
                            rows.forEach(function(item){
                                value.push(item.name);
                            });
                            $('#hukou_city').val(value.join(''));
                            this.hide();
                        }
                    });
                    $('#hukou_city').on('click', function () {
                        cityPicker.show(this);
                    });
                })();
                //选择职位分类
                var categoryPicker = new ScrollSelect({
                    source_url: Fast.api.fixurl('xilujob/job_category/job_categories'),
                    name_key: 'category_name', children_key: 'childlist',
                    data_parser: function (rawData) {
                        if(rawData.code===1) {
                            return rawData.data;
                        }
                        return [];
                    },on_select:function (selectedDatas, level, targetElement) {
                        if(level!=this.maxLevel) {
                            return;
                        }
                        $(targetElement).siblings('input:hidden').val(selectedDatas[level-1].id);
                        $(targetElement).val(selectedDatas[level-1].category_name);
                        // targetElement.childNodes[0].data = selectedDatas[level-1].category_name;
                        categoryPicker.hide();
                    }
                });
                //工作经验选择分类
                $('.select-job').on('click', function (event) {
                    // categoryPicker.maxLevel = $(this).hasClass('select-job') ? 3:2;
                    categoryPicker.show(event.target);
                }).on('change',function() {
                    if($(this).siblings('input:hidden').val()==='') {
                        $(this).val('请选择');
                    }
                });
                (function(){
                    //偏好区域选择省市区
                    var cityPicker = new ScrollSelect({
                        data:districts, max_level:2,
                        on_select:function(rows, level) {
                            var value = [];
                            rows.forEach(function(item){
                                value.push(item.name);
                            });
                            console.log(rows)
                            $('input[name=fav_province_id]').val(rows[0].id);
                            $('input[name=fav_city_id]').val(rows[1].id);
                            $('#fav_area').val(value.join(','));
                            this.hide();
                        }
                    });
                    $('#fav_area').on('click', function () {
                        cityPicker.show(this);
                    });
                })();

                // 编辑表单提交
                var $forms = $('.edit-form').data("validator-options", validatoroptions);
                $forms.find('.submit').on('click', function () {
                    $(this).closest('form').submit();
                });
                Form.api.bindevent($forms, function(data, ret) {
                    var model = data.model;
                    var moduleRelationName = moduleRelationNames[app.editing.module];
                    if(app.editing.module==='personal_tag') {
                        app.resume[moduleRelationName] = model;
                    }else if(Array.isArray(app.resume[moduleRelationName])) {
                        var length = app.resume[moduleRelationName].length;
                        var i=0;
                        for(;i<length;i++) {
                            if(app.resume[moduleRelationName][i].id==model.id) {
                                app.resume[moduleRelationName].splice(i,1,model);
                                break;
                            }
                        }
                        if(i===length) {
                            app.resume[moduleRelationName].push(model);
                        }
                    }else {
                        app.resume[moduleRelationName] = model;
                    }
                    app.closeEdit();
                    return false;
                });
            });

        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});